package com.cynteka.cyfoman.core;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * User: Sergey
 * Date: 02.08.11
 * Time: 23:19
 */
public class TaskScheduler {
    Logger logger = Logger.getLogger(TaskScheduler.class.getName());
    private List<TaskGroup> taskGroups;

    public List<TaskGroup> getTaskGroups() {
        return taskGroups;
    }

    public void setTaskGroups(List<TaskGroup> taskGroups) {
        this.taskGroups = taskGroups;
    }

    public void start() {
        int idx = 0;
        for (final TaskGroup taskGroup : taskGroups) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {

                    boolean hasActive = true;
                    while (hasActive) {
                        hasActive = false;
                        for (Task task : taskGroup.getTasks()) {
                            if (task.isActive()) {
                                hasActive = true;
                                try {
                                    task.run();
                                } catch (Exception e) {
                                    logger.log(Level.SEVERE, "Error executing task", e);
                                }
                            }
                        }
                        try {
                            Thread.sleep(taskGroup.getPeriod());
                        } catch (Exception e) {
                            logger.log(Level.SEVERE, "Error sleeping", e);
                        }
                    }
                }
            });
            thread.setDaemon(taskGroup.isDaemon());
            thread.setName("Taks scheduler thread #" + idx);
            thread.start();
            idx++;
        }
    }
}
